package handler

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"myai/core"
	"myai/core/types"
	"myai/service"
	"myai/store/model"
	"myai/store/model/req"
	"myai/utils/resp"
	"sync"
	"time"
)

type RedeemHandler struct {
	BaseHandler
	lock        sync.Mutex
	userService *service.UserService
}

func NewRedeemHandler(app *core.AppServer, db *gorm.DB, userService *service.UserService) *RedeemHandler {
	return &RedeemHandler{BaseHandler: BaseHandler{App: app, DB: db}, userService: userService}
}

// Verify godoc
// @Summary      卡密兑换
// @Description  卡密兑换
// @Tags         前台-卡密
// @Accept       json
// @Produce      json
// @Param        req   body     req.RedeemVerifyReq  true  "卡密兑换参数"
// @Success      200  {object}  types.BizVo{}
// @Router       /api/redeem/verify [post]
// @Security ApiKeyAuth
func (h *RedeemHandler) Verify(c *gin.Context) {
	var data req.RedeemVerifyReq
	if err := c.ShouldBindJSON(&data); err != nil {
		resp.ERROR(c, types.InvalidArgs)
		return
	}

	userId := h.GetLoginUserId(c)
	h.lock.Lock()
	defer h.lock.Unlock()
	// 查询兑换码
	var item model.Redeem
	res := h.DB.Where("code", data.Code).First(&item)
	if res.Error != nil {
		resp.ERROR(c, "无效兑换码！")
		return
	}

	if !item.Enabled {
		resp.ERROR(c, "当前兑换码已被禁用！")
		return
	}

	if item.RedeemedAt > 0 {
		resp.ERROR(c, "当前兑换码已使用，请勿重复使用！")
		return
	}
	// 开启事务
	tx := h.DB.Begin()
	// 增加算力
	err := h.userService.IncreasePower(int(userId), item.Power, model.PowerLog{
		Type:   types.PowerRedeem,
		Model:  "兑换码",
		Remark: fmt.Sprintf("兑换码核销，算力：%d，兑换码：%s...", item.Power, item.Code[:10]),
	})

	if err != nil {
		tx.Rollback()
		resp.ERROR(c, "使用兑换码出现错误："+err.Error())
		return
	}

	// 更新核销状态
	item.RedeemedAt = time.Now().Unix()
	item.UserId = userId
	err = tx.Updates(&item).Error
	if err != nil {
		tx.Rollback()
		resp.ERROR(c, "更新兑换码核销状态失败："+err.Error())
		return
	}
	// 提交事务
	tx.Commit()
	resp.SUCCESS(c)
}
